package com.xiaoyu.im.request;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.xiaoyu.base.entity.MessageEntity;
import com.xiaoyu.im.ChatToken;
import com.xiaoyu.im.client.IMClient;
import com.xiaoyu.im.datamodel.AppMessage;
import com.xiaoyu.im.datamodel.MessagePayload;
import com.xiaoyu.im.datamodel.MessageStatus;

public class MessageRequest {

    private final AppMessage pendingMessage;
    private AppMessage mSuccessMessage;
    private Throwable mException;
    private boolean mResend;
    private String mTypeForLog;
    private String mFromType = "";

    private MessageRequest(AppMessage message) {
        this.pendingMessage = message;
    }

    public static MessageRequest create(ChatToken chatToken, MessagePayload payload) {
        AppMessage pendingMessage = AppMessage.create(chatToken, payload);
        return new MessageRequest(pendingMessage);
    }

    public static MessageRequest fromEntity(MessageEntity entity) {
        AppMessage pendingMessage = AppMessage.fromEntity(entity);
        return new MessageRequest(pendingMessage);
    }

    @NonNull
    public AppMessage getPendingMessage() {
        return pendingMessage;
    }

    public String getLocalId() {
        return pendingMessage.localId;
    }

    public boolean isResend() {
        return mResend;
    }

    public String getChatId() {
        return pendingMessage.chatToken.getChatId();
    }

    public String getTargetUid() {
        return pendingMessage.chatToken.getUid();
    }

    public void reSend() {
        mResend = true;
        enqueue();
    }

    public void enqueue() {
        IMClient.getInstance().enqueueMessageRequest(this);
    }

    @Nullable
    public AppMessage getSuccessMessage() {
        return mSuccessMessage;
    }

    public void setSuccessMessage(AppMessage successMessage) {
        this.mSuccessMessage = successMessage;
    }

    @Nullable
    public Throwable getThrowable() {
        return mException;
    }

    public void setThrowable(Throwable throwable) {
        this.mException = throwable;
    }

    public int getStatus() {
        return pendingMessage.getStatus();
    }

    public void setStatus(@MessageStatus.MessageStatusDef int status) {
        pendingMessage.setStatus(status);
    }

    public String getTypeForLog() {
        return mTypeForLog;
    }

    public void setTypeForLog(String typeForLog) {
        mTypeForLog = typeForLog;
    }

    public String getFromType() {
        return mFromType;
    }

    public void setFromType(String fromType) {
        mFromType = fromType;
    }

    @Override
    public String toString() {
        return "MessageRequest{" +
                "pendingMessage=" + pendingMessage +
                ", mSuccessMessage=" + mSuccessMessage +
                ", mResend=" + mResend +
                ", mTypeForLog='" + mTypeForLog + '\'' +
                ", mFromType='" + mFromType + '\'' +
                '}';
    }
}
